//
//  AddressViewController.m
//  NewPro
//
//  Created by RYX on 2018/10/19.
//  Copyright © 2018年 何荧红. All rights reserved.
//

#import "AddressViewController.h"
#import "AddressCell.h"
#import "AddAddressViewController.h"
#import "AddressFooterView.h"
#import "AddAddressStore.h"
#import "AddressModel.h"
#import "EditAddressViewController.h"
#import "AddressList.h"
#import "SureOrderList.h"
#import "ConfirmOrderViewController.h"

@interface AddressViewController ()<UITableViewDelegate,UITableViewDataSource,AddressCellDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *listArr;
//@property (nonatomic,strong) UIView *footerView;

@property (nonatomic,strong) AddressFooterView *footerView;

@end

@implementation AddressViewController

- (AddressFooterView *)footerView{
    
    if (!_footerView) {
        
        _footerView = [[AddressFooterView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 120)];
        
    }
    
    return _footerView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBarWithTitle:@"管理收货地址"];
    
    [self.view addSubview:self.tableView];

    [self.tableView  mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
    }];

    [self refresh];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"AddAdressSuccess" object:nil];
    
}

- (void)refresh{
    
    //[self.view makeToastActivity:CSToastPositionCenter];
    
    AddAddressStore *store = [[AddAddressStore alloc] init];
    
    MJWeakSelf
    [store getAllAddressWithSuccess:^(NSArray * _Nonnull listArr) {
        
        weakSelf.listArr = [NSMutableArray arrayWithArray:listArr];
        [weakSelf.tableView reloadData];
        //[weakSelf.view hideToastActivity];
        
    } Failure:^(NSError * _Nonnull error) {
       
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 0.5;
        _tableView.sectionHeaderHeight = 9.5;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.5)];
        _tableView.tableFooterView = self.footerView;
        _tableView.tableFooterView.frame = CGRectMake(0, 0, ScreenWidth, 120);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    }
    
    return _tableView;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [AddressCell getHeight];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.listArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddressCell *cell = [AddressCell tempWithTableView:tableView];
    cell.indexpath = indexPath;
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.listArr[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressModel *model = _listArr[indexPath.section];
    
    UIViewController *ViewController = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
    if ([ViewController isKindOfClass:[ConfirmOrderViewController class]]) {
        
        ConfirmOrderViewController *VC = (ConfirmOrderViewController *)ViewController;
        VC.model = model;
        [self.navigationController popToViewController:VC animated:YES];
        
    }
}



#pragma mark - AddressCellDelegate
- (void)onSetLocalWithIndexPath:(NSIndexPath *)indexPath{
    
    AddressModel *model = self.listArr[indexPath.section];
    
    MJWeakSelf
    AddAddressStore *store = [[AddAddressStore alloc]init];
    [store setDefaultAdresstWithAddressId:model.uid andCustomId:[UserDefaultsManager sharedInstance].user_id Success:^{
        
        [weakSelf refresh];
        
        if (!([SureOrderList sharedInstance].selectedAdModel.uid.length > 0)) {
         
            UIViewController *ViewController = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
            if ([ViewController isKindOfClass:[ConfirmOrderViewController class]]) {
                
                ConfirmOrderViewController *VC = (ConfirmOrderViewController *)ViewController;
                
                VC.model = model;
            
        }
            
        }
        
        
    } failure:^(NSError * _Nonnull error) {
       
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

- (void)onEditBtnWithIndexPath:(NSIndexPath *)indexPath and:(nonnull UIButton *)btn{
    
    DLog(@"编辑");
    AddressModel *model = self.listArr[indexPath.section];
    [AddressList sharedInstance].selectAddressModel = model;
    
    EditAddressViewController *VC = [[EditAddressViewController alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
    
}

- (void)onDeleteBtnWithIndexPath:(NSIndexPath *)indexPath and:(nonnull UIButton *)btn{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您正在删除此地址" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        DLog(@"删除");
        
        btn.enabled = NO;
        
        AddressModel *model = self.listArr[indexPath.section];
        
        AddAddressStore *store = [[AddAddressStore alloc] init];
        MJWeakSelf
        [store deleteAddressWithId:model.uid Success:^{
            
            btn.enabled = YES;
            
            [weakSelf.listArr removeObjectAtIndex:indexPath.section];

            [weakSelf.tableView beginUpdates];

            [weakSelf.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section]withRowAnimation:UITableViewRowAnimationLeft];

            [weakSelf.tableView endUpdates];
        
    
            [weakSelf showMBPError:@"删除成功！"];
            
            [weakSelf.tableView reloadData];
            
            if ([[SureOrderList sharedInstance].selectedAdModel.uid isEqualToString:model.uid]) {
                
                UIViewController *ViewController = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
                if ([ViewController isKindOfClass:[ConfirmOrderViewController class]]) {
                    
                    ConfirmOrderViewController *VC = (ConfirmOrderViewController *)ViewController;
                    
                    BOOL haveDefaultLocation = NO;
                    for (AddressModel *model in self.listArr) {
                        
                        if ([model.isDefault isEqualToString:@"1"]) {
                            
                            VC.model = model;
                            haveDefaultLocation = YES;
                            break;
                        }
                    }
                    
                    if (!haveDefaultLocation) {
                        
                        VC.model = nil;
                    }
                    
                    
                }
            }
            
        } Failure:^(NSError * _Nonnull error) {
            
            btn.enabled = YES;
            
            [weakSelf showMBPError:[HttpTool handleError:error]];
        }];
        
    }]];
    [self presentViewController:alert animated:YES completion:^{
        
    }];

    
}

#pragma mark - 点击添加
- (IBAction)onAddBtn:(UIButton *)sender {
    
    AddAddressViewController *VC = [[AddAddressViewController alloc] init];

    [self.navigationController pushViewController:VC animated:YES];
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
